<template>
  <div class="create-post-page ">
    <h4>{{ isEditMode ? '编辑文章' : '新建文章' }}</h4>
    <UploaderFile action="/upload"
      class="d-flex align-items-center justify-content-center bg-light text-secondary w-100 my-4"
      :beforeUpload="uploadedCheck" @file-uploaded="handFileUploaded" :uploaded="uploadedData">
      <h2>点击上传头图</h2>
      <template #loading>
        <div class="d-flex">
          <div class="spinner-border text-secondary" roule='status'>
            <!-- <span class="scr-only"></span> -->
          </div>
        </div>
        <h2>上传中...</h2>
      </template>
      <template #uploaded="dataProps">
        <div class="upload-area">
          <img :src="dataProps.uploadedData.data.url" alt="">
          <h3>点击重新上传</h3>
        </div>

      </template>
    </UploaderFile>

    <ValidateForm @form-submit="onFormSubmit">
      <div class="mb-3 mt-3">
        <label for="" class="form-label">文章标题</label>
        <VaildateInput placeholder="请输入文章标题" type="text" :rules="titleRules" v-model="titleVal" @value="titleValue">
        </VaildateInput>
      </div>

      <div class="mb-3">
        <label for="" class="form-label">文章详情</label>
        <textarea ref="textArea"></textarea>
        <VaildateInput placeholder="请输入文章详情" rows="10" tag="textarea" type="text" :rules="contentRules"
          v-model="contentVal" @value="contentValue">
        </VaildateInput>
      </div>
      <template #submit>
        <button class="btn btn-primary btn-large">{{ isEditMode ? '更新文章' : '发表文章' }}</button>
      </template>
    </ValidateForm>
  </div>
</template>

<script lang="ts">
import { defineComponent, onMounted, ref } from "vue";
import { useStore } from "vuex";
import { GolbalDataProps, ResponseType, ImagePrpos, PostProps } from "@/store";
import { useRouter, useRoute } from "vue-router";
import ValidateForm from "@/components/ValidateForm.vue";
import VaildateInput, { RulesProp } from "@/components/VaildateInput.vue";
// import {PostProps} from "@/testData";
// import axios from "axios";
import UploaderFile from "./UploaderFile.vue";
import { beforUploadCheck } from '@/hooks/helper'
import createMessage from "@/hooks/createMessage";
import EasyMDE from 'easymde'


export default defineComponent({
  name: 'CreatePost',
  components: {
    ValidateForm,
    VaildateInput,
    UploaderFile
  },
  setup() {

    const textArea = ref<null | HTMLTextAreaElement>(null)

    const titleVal = ref();
    const contentVal = ref("");
    const titleValue = (val: string) => {
      titleVal.value = val;
    };
    const contentValue = (val: string) => {
      contentVal.value = val;
    };
    const router = useRouter();
    const route = useRoute();
    // 双取反，值不变，只是结果为true或者false
    const isEditMode = !!route.query.id
    const uploadedData = ref()

    const store = useStore<GolbalDataProps>();

    const titleRules: RulesProp = [
      { type: "required", message: "文章标题不能为空" },
    ];
    const contentRules: RulesProp = [
      { type: "required", message: "文章详情不能为空" },
    ];

    let imageId = ''
    const uploadedCheck = (file: File) => {
      const result = beforUploadCheck(file, {
        format: ['image/jpeg', 'image/png'], size: 1
      })

      const { passed, error } = result
      if (error === 'format') {
        createMessage('上传图片只能是JPG/PNG格式', 'error')
      }
      if (error === 'size') {
        createMessage('上传图片大小不能超过1MB', 'error')
      }
      return passed
    }

    // 图片上传成功
    const handFileUploaded = (rawData: ResponseType<ImagePrpos>) => {
      if (rawData.data._id) {
        imageId = rawData.data._id
      }
    }

    // 请求到文章的内容,在编辑时携带
    onMounted(() => {

      if (textArea.value) {
        const easyMdeInstance = new EasyMDE({ element: textArea.value })
      }

      if (isEditMode) {
        store.dispatch('fetchPost', route.query.id).then((rawData: ResponseType<PostProps>) => {
          // 获取请求过来的数据
          const currentPost = rawData.data
          // 如果存在就赋值
          if (currentPost.image) {
            uploadedData.value = { data: currentPost.image }
          }
          titleVal.value = currentPost.title
          contentVal.value = currentPost.content || ''
        })
      }
    })


    const onFormSubmit = (result: boolean) => {
      if (result) {
        const { column, _id } = store.state.user

        if (column) {
          const newPost: PostProps = {
            // _id: '',
            title: titleVal.value,
            content: contentVal.value,
            column,
            createdAt: new Date().toLocaleString(),//发布时间
            author: _id
          }
          if (imageId) {
            newPost.image = imageId
          }

          // 判断时修改还是新建
          const actionName = isEditMode ? 'updatePost' : 'createPost'
          const sendData = isEditMode ? {
            id: route.query.id,
            payload: newPost
          } : newPost

          // createMessage('新建成功', 'success')
          //  自动跳转到详情页
          store.dispatch(actionName, sendData).then(() => {
            createMessage('发布成功，2秒后跳转', 'success')
            //根据路由命名来跳转
            router.push({ name: 'column', params: { id: column } })
          })
        }
      }
    }


    /* const handFileChange = (e: Event) => {
      console.log(e);
      // 在这个input组件中，我们可以拿到它选择的file对象，也就是文件对象
      const target = e.target as HTMLInputElement //一个input框元素
      //  注意这个files列表，也就是fileList对象，他是一个array-link 的object的
      // 一个伪数组的对象,支持多个文件
      const files = target.files
      if (files) {
        // 拿第一项，就是我们选择的文件
        const upladedFile = files[0]
        console.log(upladedFile.name);

        // 我们来模拟表单的数据，我们可以使用FormData对象，这是另一种针对XHR2设计的新数据类型
        //使用 FormData能够很方便的实现以JacaScript创建HTML
        //表单数据串联化--- name=zhang&age=13这种方式
        const formData = new FormData()
        // 通过append方法为其附加了<input>值
        // 第一项 数据对应的表单名称
        // 第二项 表单的值
        formData.append(upladedFile.name, upladedFile)
        console.log(formData);
        axios.post('/upload', formData, {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        }).then(resp => {
          console.log(resp);

        })

      }
    } */
    return {
      textArea,
      titleRules,
      contentRules,
      onFormSubmit,
      titleVal,
      contentVal,
      contentValue,
      titleValue,
      uploadedCheck,
      handFileUploaded,
      isEditMode,
      uploadedData,

      // handFileChange
    }
  }
})
</script>

<style>
.create-post-page .file-upload-container {
  height: 200px;
  /* cursor : 网页浏览时用户鼠标指针的样式或图形形状。
属性值：pointer：光标为一只手 */
  cursor: pointer;
  overflow: hidden;
}

.create-post-page .file-upload-container img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.upload-area {
  position: relative;
}

.upload-area:hover h3 {
  display: block;
}

.upload-area h3 {
  display: none;
  position: absolute;
  color: #999;
  text-align: center;
  width: 100%;
  top: 50%;
}
</style>